//
//  CSSRefreshContol.swift
//  weibo28
//
//  Created by chushushan on 16/5/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

enum RefreshState: Int {
    //下拉刷新状态
    case Normal = 0
    //松手就刷新状态
    case Pulling = 1
    //正在刷新
    case Refreshing = 2
}


//  当前刷新控件的高度
let RefreshControlH: CGFloat = 50


class CSSRefreshContol: UIControl {

  //当前滚动的视图
    private var currentScrollView: UIScrollView?
    
    //当前状态
    private var refreshState: RefreshState = .Normal {
    
        didSet {
            switch refreshState {
            case .Normal:
                //  显示下拉刷新文本，停止菊花转，按钮重置动画print("显示下拉刷新文本，显示箭头，停止菊花转，按钮重置动画")
                iconView.hidden = false
                messageLabel.text = "下拉刷新"
                indicatorView.stopAnimating()
                //  重置箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformIdentity
                })
                
                //  判断上一次是刷新状态，设置为原始的contentInset
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= RefreshControlH
                    })
                }
                
                
            case .Pulling:
                // print("显示松手就刷新文本，箭头调转")
                messageLabel.text = "松手就刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                //  print("显示正在刷新文本，菊花转起来，下拉箭头隐藏")
                messageLabel.text = "正在刷新"
                iconView.hidden = true
                indicatorView.startAnimating()
                
                //  发送事件
                sendActionsForControlEvents(.ValueChanged)
                
                //  设置停留
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += RefreshControlH
                })
            }
        }
    }
    
    //icon
    private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //转菊花
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    //消息文本
    private lazy var messageLabel: UILabel = {
    
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
    
    }()
    
    
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
    
        backgroundColor = UIColor.whiteColor()
        
        addSubview(iconView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(iconView)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(iconView.snp_right)
            make.centerY.equalTo(self)
        }
    
    }
    
    
    //拿到父视图
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        // 判断我们的父视图能否强转成我们需要的滚动视图，如果可以我们可以监听tableview的一个滚动使用kvo
        guard let scrollView = newSuperview as? UIScrollView else {
        return
        
        }
        
        //设置frame
        self.frame.size = CGSizeMake(scrollView.frame.size.width, RefreshControlH)
        self.frame.origin.y = -RefreshControlH
         
        
        //kvo监听2
       
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
        
        self.currentScrollView = scrollView
        
    }
    
    //监听的事件
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
//        print(currentScrollView?.contentOffset.y)
        
        
        //dragging就是拖动状态
        if currentScrollView!.dragging {
        //拖动情况下只有两种状态。1.下拉刷新状态 2.松手刷新
            //计算临界点
            let maxY = -(currentScrollView!.contentInset.top + RefreshControlH)
            //偏移量
            
 //**********************
//不能取绝对值，因为偏移量有方向性，当取绝对值的时候，正值是上拉，当大于临界点时，变成pulling状态，停止拖动直接变成.Refreshing刷新状态，所以会发送事件
 //**********************
            
//            let contentOffSetY = abs(currentScrollView!.contentOffset.y)
            let contentOffSetY = currentScrollView!.contentOffset.y
            //如果当前的偏移量da于临界点则是pulling状态
            if contentOffSetY < maxY && refreshState == .Normal {
            //当前进入pulling状态
                refreshState = .Pulling
//            print("Pulling")
            } else if contentOffSetY >= maxY && refreshState == .Pulling {
            //是nomal状态
                refreshState = .Normal
//                print("Normal")
            }
            
            
        } else {
        //松手状态下，要想进入刷新状态，1.上一次是松手就刷新状态，冰球还要松手
//            print("松手")
            if refreshState == .Pulling {
//            print("刷新状态")
                refreshState = .Refreshing
            }
            
        
        }
        
        
    }
    
    
    //谨记，移除kvo
    deinit {
    
        currentScrollView!.removeObserver(self, forKeyPath: "contentOffset")
    
    }
    
    
    func endRefreshing() {
    
        refreshState = .Normal
    }
    

}
